﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Databases : SecPage
{
    ProxyWrapper.UserProxy.UserDetails objUser = null;
    private string Sorting = string.Empty;
    private string Order = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userObject"] == null)
        {
            Response.Redirect("Default.aspx");
        }
        else
        {
            objUser = ((ProxyWrapper.UserProxy.UserDetails)Session["userObject"]);
            if (Request.QueryString != null && Request.QueryString["msg"] != null)
            {
                showMessages.Visible = true;
                mmsg.InnerText = Request.QueryString["msg"].ToString();
            }
            string sortOrder = Enums.UserSorting.time.ToString();
            if (Request.QueryString != null && Request.QueryString["order"] != null)
            {
                sortOrder = Request.QueryString["order"].ToString();
            }
            DrawPage((Enums.UserSorting)Enum.Parse(typeof(Enums.UserSorting), sortOrder));
            if (Request.QueryString["exportdatabase"] != null && Request.QueryString["exportdatabase"].ToString() == "true"
                && Request.QueryString["dbid"] != null)
            {
                int dbId = 0;
                if (Int32.TryParse(Request.QueryString["dbid"], out dbId) && dbId > 0)
                {
                    ExportDatabase(dbId);
                }
            }
        }
    }

    private void ExportDatabase(int dbId)
    {
        ProxyWrapper.DatabaseServiceWrapper _dbWrapper = new ProxyWrapper.DatabaseServiceWrapper();
        try
        {
            string dbName = "";
            dbName = Request.QueryString["dbname"] != null ? Request.QueryString["dbname"].ToString() : "ExportedDatabase";
            ProxyWrapper.DatabaseServiceWrapper _wrapper = new ProxyWrapper.DatabaseServiceWrapper();
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=" + dbName + ".csv");
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.xls";
            Response.Write(_wrapper.ExportDatabase(dbId, objUser.ClientId));
            Response.End();
        }
        catch (Exception)
        {
        }
    }
    public string GetRowCount(string rowCount)
    {
        int _Count = 0;
        if (Int32.TryParse(rowCount, out _Count) && _Count > 0)
        {
            return _Count.ToString() + " Values";
        }
        return "<i>Empty</i>";
    }
    public string GetCaseSensitiveValidation(string val)
    {
        bool isTrue = false;
        if (bool.TryParse(val, out isTrue) && isTrue)
        {
            return "<dt><img src='Images/case16.png'/></dt><dd>Case-Sensitive Validation</dd>";
        }
        return "";
    }
    private void DrawPage(Enums.UserSorting sortorder)
    {
        ProxyWrapper.DatabaseServiceWrapper _dbWrapper = new ProxyWrapper.DatabaseServiceWrapper();
        List<ProxyWrapper.CommonProxyService.DatabaseDetails> objDBList = _dbWrapper.GetDBList(objUser.ClientId);

        switch (sortorder)
        {
            case Enums.UserSorting.time:
                objDBList = objDBList.OrderByDescending(m => m.LastUpdated).ToList<ProxyWrapper.CommonProxyService.DatabaseDetails>();
                dateSorter.Style.Add("font-weight", "bolder");
                dateSorter.Style.Add("color", "#000");
                break;
            case Enums.UserSorting.alpha:
                objDBList = objDBList.OrderBy(m => m.DBName).ToList<ProxyWrapper.CommonProxyService.DatabaseDetails>();
                nameSorter.Style.Add("font-weight", "bolder");
                nameSorter.Style.Add("color", "#000");
                break;
            case Enums.UserSorting.service:
                for (int i = 0; i < objDBList.Count; i++)
                {
                    if (objDBList[i].GetServiceDetails == null)
                    {
                        objDBList[i].GetServiceDetails = new DataSet();
                        objDBList[i].GetServiceDetails.Tables.Add(new DataTable());
                    }

                }
                objDBList = objDBList.OrderByDescending(m => m.GetServiceDetails.Tables[0].Rows.Count).ToList<ProxyWrapper.CommonProxyService.DatabaseDetails>();
                serviceSorter.Style.Add("font-weight", "bolder");
                serviceSorter.Style.Add("color", "#000");
                break;
            default:
                objDBList = objDBList.OrderByDescending(m => m.LastUpdated).ToList<ProxyWrapper.CommonProxyService.DatabaseDetails>();
                dateSorter.Style.Add("font-weight", "bolder");
                dateSorter.Style.Add("color", "#000");
                break;
        }
        if (objDBList != null && objDBList.Count > 0 && objDBList[0].DbId > 0)
        {
            dbCount.InnerText = "Showing " + (objDBList.Count > 0 ? 1 : 0).ToString() + " - " + objDBList.Count.ToString() + " of " + objDBList.Count.ToString() + " rosters.";
            databasesList.DataSource = objDBList;
            databasesList.DataBind();
        }
        else
        {
            databasesList.DataSource = new object[] { };
            databasesList.DataBind();
        }
    }

    public string GetServiceCount(string dbId)
    {
        List<ProxyWrapper.CommonProxyService.DatabaseDetails> objDataServiceList = ((List<ProxyWrapper.CommonProxyService.DatabaseDetails>)databasesList.DataSource);
        // Dictionary<int, string> dcServices = objUserList.First(m => m.UserId.ToString() == userId).GetServiceList;
        DataTable dcServices = objDataServiceList.First(m => m.DbId.ToString() == dbId).GetServiceDetails == null ? null : objDataServiceList.First(m => m.DbId.ToString() == dbId).GetServiceDetails.Tables[0];
        if (dcServices != null && dcServices.Rows.Count > 0)
            return "<span class='numberOfServices'>" + dcServices.Rows.Count.ToString() + " Buttons...</span>" + GetServiceDetails(dcServices);
        else
            return "<i>Not associated with any buttons.</i>";

    }

    private string GetServiceDetails(DataTable dcServices)
    {
        StringBuilder sb = new StringBuilder();
        if (dcServices != null)
        {
            sb.Append("<span class='serviceList' style='display: none;'>");
            for (int i = 0; i < dcServices.Rows.Count; i++)
            {
                sb.Append(" <a href='Services.aspx?serviceId=" + dcServices.Rows[i][0].ToString() + "'>" + dcServices.Rows[i][1].ToString() + "</a> ");
                sb.Append(",");
            }

        }
        if (sb != null && sb.Length > 0)
        {
            sb = sb.Remove(sb.Length - 1, 1);
        }
        sb.Append("</span>");
        sb.Append("    <a class='sClickToShow' style='text-decoration:underline;'>Click to show</a>");
        return sb.ToString();
    }
    public string GetDBImage(string rowCount)
    {
        int _Count = 0;
        if (Int32.TryParse(rowCount, out _Count) && _Count > 0)
        {
            return "Images/database-normal.png";
        }
        return "Images/database-inactive.png";
    }
}